package com.sincetimes.game.util;

import java.io.IOException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Web宸ュ叿绠�
 * 
 * @author xiaoxi zhang
 */
public class WebUtil {

	public static final SimpleDateFormat yformat = new SimpleDateFormat("yyyy年MM月dd日HH点mm分");
	public static final SimpleDateFormat dashedFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
	public static final SimpleDateFormat qqpaylogformat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	public static final SimpleDateFormat qqbillfiledate = new SimpleDateFormat("yyyyMMdd");
	public static final SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
	public static final SimpleDateFormat ymd2Format = new SimpleDateFormat("yyyyMMdd");
	public static final DecimalFormat perFormat = new DecimalFormat("0.00");
	public static final Random random = new Random(System.currentTimeMillis());

	static MessageDigest md;
	static {
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			md = null;
		}
	}

	public static String getMD5Code(String text) {
		if (md != null) {
			try {
				return byte2hexString(md.digest(text.getBytes("GBK")));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return text;
	}

	public static String byte2hexString(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}

	public static long getStartOfDay(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	public static long getStartOfWeek(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	public static long getStartOfMonth(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	/**
	 * 杩斿洖鎸囧畾鏃ユ湡鐨勬绉掓暟
	 * 
	 * @param str
	 * @return
	 */
	public static long parseStringToTime(String str) throws java.text.ParseException,
			java.lang.NullPointerException {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		java.util.Date date = format.parse(str);
		return date.getTime();
	}

	public static int between(int min, int max, int value) {
		return Math.max(min, Math.min(max, value));
	}

	public static void sendJSON(HttpServletResponse response, String json) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(json);
	}

	public static JSONObject getJsonResult(int code) {
		JSONObject json = new JSONObject();
		try {
			json.put("code", code);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}

	public static Cookie initCookie(String name, String value, boolean remove) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(remove ? 0 : Integer.MAX_VALUE);
		cookie.setPath("/");
		return cookie;
	}

	public static void setAdminCookie(HttpServletResponse response, String id) {
		response.addCookie(initCookie("colmaster_admin_id", id, false));
		response.addCookie(initCookie("colmaster_admin_hash", getMD5Code("$^&%&*-" + id), false));
	}

	public static void removeAdminCookie(HttpServletResponse response) {
		response.addCookie(initCookie("colmaster_admin_id", "", true));
		response.addCookie(initCookie("colmaster_admin_hash", "", true));
	}

	public static long getAdminCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String id = null, hash = null;
		if (cookies == null) {
			return 0;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("colmaster_admin_id")) {
				id = c.getValue();
			} else if (c.getName().equals("colmaster_admin_hash")) {
				hash = c.getValue();
			}
		}
		if (id != null && hash != null) {
			if (getMD5Code("$^&%&*-" + id).equals(hash)) {
				try {
					return Long.parseLong(id);
				} catch (Exception e) {
				}
			}
		}
		return 0;
	}

	public static String safeJsonString(JSONObject json, String name) {
		try {
			return json.getString(name);
		} catch (JSONException exception) {
			return "";
		}
	}

	public static String getRequestIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 鏍￠獙String, String涓嶈兘涓簄ull 鎴栭暱搴�=0
	 * 
	 * @param args
	 *            涓�覆String瀵硅薄
	 * @return true String瀵硅薄鍏ㄩ儴鏍￠獙姝ｇ‘
	 */
	public static Boolean verifyInputString(String... args) {
		for (String s : args) {
			if (s == null || s.length() <= 0)
				return false;
		}
		return true;
	}

	/**
	 * 鏍￠獙String, String涓嶈兘涓簄ull 鎴栭暱搴�=0
	 * 
	 * @param arg
	 *            涓�釜String瀵硅薄
	 * @return true String瀵硅薄鏍￠獙姝ｇ‘
	 */
	public static Boolean verifyInputString(String arg) {
		if (arg == null || arg.length() <= 0) {
			return false;
		}
		return true;
	}

	/**
	 * 妫�祴鏄惁涓鸿吘杩匫penId鎴朞penKey鏍煎紡
	 * 
	 * @param arg
	 * @return
	 */
	public static Boolean isOpenIdOpenKeyFormat(String... args) {

		if (!verifyInputString(args))
			return false;

		for (String arg : args) {
			for (int i = 0; i < arg.length(); i++) {
				char c = arg.charAt(i);
				if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70))) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 鏁版嵁缁熻绯荤粺鑱斿悎鏃朵娇鐢ㄧ殑瀵嗙爜
	 * 
	 * @return
	 */
	public static String getDynSign() {
		return WebUtil.getMD5Code(WebUtil.ymd2Format.format(new Date()) + "%*!");
	}
	
	//渚濇嵁鎸囧畾鏃ユ湡鐨勬绉掓暟锛岃繑鍥炴棩鏈熷瓧绗︿覆
	private static String getDate(long milseconds) {
		long begindate =milseconds;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(new Date(begindate));
	}

}
